import { useEffect } from 'react'

import { getUserServiceObjectListApi, queryOrgTreeApi, saveOrUpdateApi } from '@/api/sys/organization'
import { qualificationTypeAllApi } from '@/api/sys/qualificationType'
import { queryRoleTreeApi } from '@/api/sys/roleManage'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { REGEXP_PASSWORD, REGEXP_USERNAME } from '@/utils/constants'
import { SYS_USER_POSITION_ENUM } from '@/utils/enum'
import { requestWithTry } from '@/utils/request'

const EditModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { id } = row

  useEffect(() => {
    if (!id) return
    form.setFieldsValue({
      ...row,
      serviceObjectList: row.serviceObjectList?.map(({ serviceObjectId }) => serviceObjectId),
      qualificationTypeList: row.qualificationTypeList?.map(({ id }) => id),
      qualificationFileList: row.qualificationFileList?.map(file => ({
        name: file,
        url: file,
      })),
    })
  }, [id])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'fullName',
      label: '姓名',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'Input',
        props: {
          maxLength: 20,
          placeholder: '10个字以内',
        },
      },
    },
    {
      field: 'userName',
      label: '用户名',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_USERNAME,
            message: '格式有误，需满足3-16位',
          },
        ],
      },
      component: { name: 'Input', props: { disabled: id } },
    },
    {
      exclude: id,
      field: 'password',
      label: '密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
    {
      exclude: id,
      field: 'confirmedPassword',
      label: '确认密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
    {
      field: 'departmentId',
      label: '组织架构',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekTreeSelect',
        props: {
          api: queryOrgTreeApi,
          fieldNames: { value: 'departmentId', label: 'departmentName' },
        },
      },
    },
    {
      field: 'roleIds',
      label: '角色',
      formItemProps: {
        rules: [{ required: true }],
      },
      component: {
        name: 'AekTreeSelect',
        props: {
          api: queryRoleTreeApi,
          fieldNames: { value: 'roleId', label: 'roleName' },
          treeCheckable: true,
        },
      },
    },
    {
      field: 'mobileNumber',
      label: '手机号',
      component: { name: 'Input' },
    },
    {
      field: 'jobNumber',
      label: '工号',
      component: { name: 'Input' },
    },
    {
      field: 'dingUserId',
      label: '钉钉userId',
      component: { name: 'Input' },
    },
    {
      field: 'userPosition',
      label: '岗位',
      component: { name: 'Select', props: { options: SYS_USER_POSITION_ENUM.options } },
    },
    {
      field: 'serviceObjectList',
      label: '擅长内容',
      component: {
        name: 'AekTreeSelect',
        props: {
          api: getUserServiceObjectListApi,
          fieldNames: { value: 'serviceObjectId', label: 'serviceObjectName', children: 'childList' },
          treeCheckable: true,
        },
      },
    },
    {
      field: 'qualificationTypeList',
      label: '资质类型',
      component: {
        name: 'AekSelect',
        props: {
          api: qualificationTypeAllApi,
          fieldNames: { value: 'id', label: 'qualificationTypeName' },
          mode: 'multiple',
        },
      },
    },
    {
      field: 'qualificationFileList',
      label: '资质证书',
      formItemProps: {
        help: '支持扩展名：.png .jpg .jpeg .bmp .pdf .doc .docx',
      },
      component: {
        name: 'AekUpload',
        props: { fileType: 'unset' },
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      userId: row.userId,
      ...values,
      serviceObjectList: values.serviceObjectList?.map(id => ({ serviceObjectId: id, source: 0 })),
      qualificationTypeList: values.qualificationTypeList?.map(id => ({ id })),
      qualificationFileList: values.qualificationFileList?.map(({ url }) => url),
    }
    await requestWithTry(saveOrUpdateApi, params)
  }
  return (
    <AekModal title={id ? '编辑' : '新增'} width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

EditModal.PromiseThen = PromiseThen

export default EditModal
